<?php

namespace interface\v1;

// 订货系统 订单接口
use verify;

class orderStoreClass extends index
{
	private const  table        = 'store_client';
	private const  tableAddress = 'store_client_address';
	private const  tableTarget  = 'kehu';

	private static string $cid  = 'ab3c4d8d235c26ff';
	private static string $khid = 'aff27e1a45c3ab73';
	// private $coid   = 'a1ce4e3b611ee192';

	/**
	 * 首页
	 *
	 * @return void
	 */
	public function home()
	{
		$this->code       = 1;
		$info             = query(self::table, " id = '" . self::$cid . "' ");
		$kehu             = query(self::tableTarget, " khid = '{$info['khid']}' ");
		$data['userInfo'] = [
			'avatarUrl'   => root . 'img/miniProgram/store/header.svg',
			'nickName'    => $info['name'],
			'phoneNumber' => $info['tel'],
			'gender'      => $info['gender'],
			'khid'        => $info['khid'],
		];
		// 订单统计
		$data['orderTagInfos'] = [
			[
				'orderNum' => 1, 'tabType' => 5, 'type' => '待下单',
			], [
				'orderNum' => 2, 'tabType' => 10, 'type' => '待确认',
			], [
				'orderNum' => 1, 'tabType' => 40, 'type' => '待发货',
			], [
				'orderNum' => 0, 'tabType' => 0, 'type' => '已完成',
			],
		];
		// 统计信息
		$data['countsData'] = [
			[
				'num' => 2, 'name' => '积分', 'type' => 'point',
			],
			[
				'num' => 10, 'name' => '优惠券', 'type' => 'coupon',
			],
		];
		// 客服信息
		$data['customerServiceInfo'] = [
			'servicePhone'        => '4006336868',
			'serviceTimeDuration' => '每周三至周五 9:00-12:00  13:00-15:00',
		];
		// 企业信息
		$data['company']    = [
			'info'    => [
				'companyName' => $kehu['companyName'],
				'nature'      => $kehu['nature'],
				'contactName' => $kehu['contactName'],
				'contactTel'  => $kehu['contactTel'],
				'website'     => $kehu['website'],
				'email'       => $kehu['email'],
				'address'     => $kehu['region'] . $kehu['address'],
			],
			// 开票信息
			'invoice' => [
				'companyBank'    => $kehu['companyBank'],
				'companyNum'     => $kehu['companyNum'],
				'companyBankNum' => $kehu['companyBankNum'],
				'companyAddress' => $kehu['companyAddress'],
			],
		];
		$this->resp['data'] = $data;
	}

	/**
	 * 获取订单类型
	 *
	 * @return void
	 */
	public function getOrder()
	{
		$this->code = 1;
		$where      = '';
		(int)$page = (is_numeric($this->get('p'))) ? abs($this->get('p')) : 1;    //页码
		(int)$num = (is_numeric($this->get('num'))) ? abs($this->get('num')) : 6; //条数
		$page  = $page > 0 ? $page : 1;
		$start = ($page - 1) * $num;                                              //起始位置
		$limit = "  LIMIT $start,$num ";
		$sql   = " SELECT `id`, `orderNo`, state as `statusDesc`, money as `amount`  FROM `store_order` WHERE ";
		$order = ' ORDER BY `time` DESC'; //排序
		$state = in_array($this->post('state'), ['待下单', '待确认', '待发货', '已发货',]) ? $this->post('state') : '';
		$where = generateWhere([
			'coid' => self::$coid,
			'khid' => self::$khid,
		]);
		if ($state) {
			$where .= " AND state = '$state' ";
		}
		$sql   = $sql . $where . $order . $limit;
		$res   = sqlFind($sql);
		$thumb = root . 'img/miniProgram/store/thumb.png';
		foreach ($res as $key => $item) {
			$goods     = find([
				'table' => 'store_order_detail',
				'where' => " orderId = '{$item['id']}' ",
			]);
			$goodsList = [];
			foreach ($goods['array'] as $good) {
				$material    = query('material', " id = '$good[materialId]' ");
				$goodsList[] = [
					'id'              => $good['id'],
					'thumb'           => $thumb,
					'title'           => $material['name'] . $material['code'] . $material['model'],
					'skuId'           => $material['id'],
					'spuId'           => $good['spid'],
					'specs'           => [$material['name']],
					'price'           => $good['price'],
					'num'             => $good['num'],
					'titlePrefixTags' => '',
				];
			}
			$res[$key]['goodsList']   = $goodsList;
		}
		if (!$res) {
			$this->resp['warn'] = '暂无结果';
		} else {
			$this->resp = [
				'data' => $res,
			];
		}
	}

	/**
	 * 创建订单
	 *
	 * @return void
	 */
	public function putOrder()
	{
		$string = $this->post('params');
		$array  = json_decode(self::htmlDecode($string), true);
		if (empty($array)) {
			$this->resp['warn'] = '参数错误';
		} else {
			$id      = self::getId();
			$orderNo = app::generateCode('store_order', [
				'prefix' => 'DHDD' . date('Ymd', strtotime($this->date)),
				'table'  => 'store_order',
				'field'  => 'orderNo',
				'where'  => " and coid = '" . self::$coid . "'",
			], []);
			$warn    = static::insert([
				'table' => 'store_order',
				'field' => [
					'id'           => $id,
					'coid'         => self::$coid,
					'text'         => '',
					'type'         => '商城订货',
					'khid'         => self::$khid,
					'name'         => $array['userAddressReq']['name'],
					'tel'          => $array['userAddressReq']['phoneNumber'],
					'address'      => $array['userAddressReq']['region'] . $array['userAddressReq']['address'],
					'orderDate'    => $this->date,
					'deliveryDate' => '',
					'orderNo'      => $orderNo,
					'manager'      => '',
					'money'        => 0,
					'state'        => '待下单',
				],
			]);
			if ($warn == '新增成功') {
				$total = 0;
				foreach ($array['goodsRequestList'] as $item) {
					// 前端未选择的
					if (!$item['isSelected']) {
						continue;
					}
					$material     = query('material', " id = '{$item['materialId']}' ");
					$storeProduct = query('store_product', " materialId = '$item[skuId]' AND coid = '" . self::$coid . "'  ");
					$clientPrice  = query('store_client_price', generateWhere([
						'coid'          => self::$coid,
						'khid'          => self::$khid,
						'materialId' => $item['skuId'],
					]));
					$price        = $clientPrice['dealPrice'] ?: $storeProduct['price'];
					$num          = abs($item['quantity']);
					$money        = $price * $num;
					// $money        = $price * $num * (1 + $material['saleRate']);
					static::update([
						'table' => 'store_order_detail',
						'field' => [
							'orderId'  => $id,
							'orderNum' => $num,
							'num'      => $num,
							'unit'     => $material['unit'],
							'price'    => $price,
							'rate'     => $material['saleRate'],
							'money'    => $money,
						],
						'where' => generateWhere([
							'ctid'          => self::$cid,
							'spid'          => $item['spuId'],
							'materialId'    => $item['materialId'],
						]),
					]);
					$total += $money;
				}
				static::update([
					'table' => 'store_order',
					'field' => [
						'money' => $money,
					],
					'where' => " id = '$id' ",
				]);
				$this->code = 1;
				$warn       = '处理成功';
			}

			$this->resp['warn'] = $warn;
		}
	}

	/**
	 * 删除订单
	 *
	 * @return void
	 */
	public function delOrder() {}

}
